<template>
  <div class="user-info-container">
    <div class="user-info-card">
      <div class="card-header">
        <h2>用户信息</h2>
        <el-button
          type="primary"
          :icon="Refresh"
          @click="refreshInfo"
          :loading="refreshLoading"
          circle
        />
      </div>

      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="userInfo" class="user-info-content">
        <!-- 查看模式 -->
        <div v-if="!isEditing" class="view-mode">
          <div class="avatar-section">
            <el-avatar :src="userAvatar" :size="80" />
            <div class="user-basic-info">
              <h3>{{ userInfo.name }}</h3>
              <p class="user-role">{{ roleText }}</p>
            </div>
          </div>

          <div class="info-grid">
            <div class="info-item">
              <label>用户ID</label>
              <span>{{ userInfo.id }}</span>
            </div>
            <div class="info-item">
              <label>用户名</label>
              <span>{{ userInfo.account }}</span>
            </div>
            <div class="info-item">
              <label>角色</label>
              <span>{{ roleText }}</span>
            </div>
            <div class="info-item">
              <label>注册时间</label>
              <span>{{ registerTime }}</span>
            </div>
          </div>

          <div class="actions">
            <el-button type="primary" @click="enterEditMode">
              <el-icon><Edit /></el-icon>
              编辑信息
            </el-button>
            <el-button @click="refreshInfo" :loading="refreshLoading">
              <el-icon><Refresh /></el-icon>
              刷新信息
            </el-button>
            <el-button @click="logout">
              <el-icon><SwitchButton /></el-icon>
              退出登录
            </el-button>
          </div>
        </div>

        <!-- 编辑模式 -->
        <div v-else class="edit-mode">
          <el-form
            ref="userFormRef"
            :model="editForm"
            :rules="rules"
            label-width="100px"
          >
            <div class="avatar-section">
              <el-avatar :src="userAvatar" :size="80" />
              <div class="user-basic-info">
                <h3>{{ editForm.name }}</h3>
                <p class="user-role">{{ roleText }}</p>
              </div>
            </div>

            <div class="form-grid">
              <el-form-item label="用户ID">
                <el-input v-model="editForm.id" disabled />
              </el-form-item>
              <el-form-item label="用户名">
                <el-input v-model="editForm.account" disabled />
              </el-form-item>
              <el-form-item label="姓名" prop="name">
                <el-input v-model="editForm.name" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="角色">
                <el-input v-model="roleText" disabled />
              </el-form-item>
            </div>

            <div class="edit-actions">
              <el-button
                type="primary"
                @click="saveUserInfo"
                :loading="saveLoading"
              >
                保存信息
              </el-button>
              <el-button @click="cancelEdit">取消</el-button>
              <el-button type="warning" @click="showPasswordDialog">
                <el-icon><Key /></el-icon>
                修改密码
              </el-button>
            </div>
          </el-form>
        </div>
      </div>

      <div v-else class="error">
        <el-icon class="error-icon"><Warning /></el-icon>
        <p>无法获取用户信息</p>
        <el-button type="primary" @click="fetchUserInfo" :loading="loading">
          <el-icon><Refresh /></el-icon>
          重新获取
        </el-button>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
      :before-close="handlePasswordDialogClose"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="80px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码（至少6位）"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="updatePassword"
            :loading="passwordLoading"
          >
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, SwitchButton, Warning, Edit, Key } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo, updateUserPassword } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

const userInfo = ref(null)
const loading = ref(true)
const refreshLoading = ref(false)
const saveLoading = ref(false)
const passwordLoading = ref(false)
const isEditing = ref(false)
const passwordDialogVisible = ref(false)

// 表单引用
const userFormRef = ref()
const passwordFormRef = ref()

// 编辑表单
const editForm = reactive({
  id: '',
  account: '',
  name: '',
  role: ''
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度为2-20个字符', trigger: 'blur' }
  ]
}

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 计算属性
const roleText = computed(() => {
  if (!userInfo.value) return ''
  return userInfo.value.role === 'admin' ? '管理员' : '普通用户'
})

const registerTime = computed(() => {
  // 这里可以添加注册时间的处理逻辑
  return '2025-01-01'
})

const userAvatar = computed(() => {
  if (userInfo.value && userInfo.value.account === 'admin') {
    return new URL('@/assets/imgs/login/icon-admin.png', import.meta.url).href
  } else if (userInfo.value && userInfo.value.account === 'user') {
    return new URL('@/assets/imgs/login/icon-user.png', import.meta.url).href
  }
  return 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    const res = await getUserInfo()

    if (res.code === 200) {
      userInfo.value = res.data
      // 如果在编辑模式，同步更新编辑表单
      if (isEditing.value) {
        editForm.id = res.data.id
        editForm.account = res.data.account
        editForm.name = res.data.name
        editForm.role = res.data.role
      }
      ElMessage.success('用户信息获取成功')
    } else {
      ElMessage.error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新用户信息
const refreshInfo = async () => {
  try {
    refreshLoading.value = true
    const res = await getUserInfo()

    if (res.code === 200) {
      userInfo.value = res.data
      // 如果在编辑模式，同步更新编辑表单
      if (isEditing.value) {
        editForm.id = res.data.id
        editForm.account = res.data.account
        editForm.name = res.data.name
        editForm.role = res.data.role
      }
      ElMessage.success('用户信息已刷新')
    } else {
      ElMessage.error(res.message || '刷新用户信息失败')
    }
  } catch (error) {
    console.error('刷新用户信息失败:', error)
    ElMessage.error('刷新用户信息失败，请稍后重试')
  } finally {
    refreshLoading.value = false
  }
}

// 进入编辑模式
const enterEditMode = () => {
  // 初始化编辑表单
  editForm.id = userInfo.value.id
  editForm.account = userInfo.value.account
  editForm.name = userInfo.value.name
  editForm.role = userInfo.value.role
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!userFormRef.value) return

  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        saveLoading.value = true
        const res = await updateUserInfo({ name: editForm.name })

        if (res.code === 200) {
          ElMessage.success('用户信息更新成功')
          // 更新用户信息
          userInfo.value = res.data
          // 更新用户存储中的信息
          userStore.setUserInfo(res.data)
          // 退出编辑模式
          isEditing.value = false
        } else {
          ElMessage.error(res.message || '更新用户信息失败')
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新用户信息失败，请稍后重试')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 显示修改密码对话框
const showPasswordDialog = () => {
  // 重置密码表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
  passwordDialogVisible.value = true
}

// 处理密码对话框关闭
const handlePasswordDialogClose = (done) => {
  ElMessageBox.confirm('确认要关闭修改密码对话框吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

// 修改密码
const updatePassword = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        passwordLoading.value = true
        const res = await updateUserPassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        })

        if (res.code === 200) {
          ElMessage.success('密码修改成功，请重新登录')
          passwordDialogVisible.value = false
          // 1秒后跳转到登录页
          setTimeout(() => {
            userStore.clearUserInfo()
            window.location.href = '/login'
          }, 1000)
        } else {
          ElMessage.error(res.message || '修改密码失败')
        }
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改密码失败，请稍后重试')
      } finally {
        passwordLoading.value = false
      }
    }
  })
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 清除用户信息
    userStore.clearUserInfo()
    // 跳转到登录页
    router.push('/login')
    ElMessage.success('已退出登录')
  }).catch(() => {
    // 取消退出
  })
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped lang="scss">
.user-info-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;

  .user-info-card {
    width: 100%;
    max-width: 600px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 30px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;

      h2 {
        margin: 0;
        color: #333;
      }
    }

    .loading {
      text-align: center;
      padding: 50px 0;

      .spinner {
        border: 4px solid #f3f3f3;
        border-top: 4px solid #409eff;
        border-radius: 50%;
        width: 40px;
        height: 40px;
        animation: spin 1s linear infinite;
        margin: 0 auto 15px;
      }

      p {
        color: #666;
      }
    }

    .user-info-content {
      .view-mode {
        .avatar-section {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-bottom: 30px;

          .user-basic-info {
            text-align: center;
            margin-top: 15px;

            h3 {
              margin: 0 0 5px 0;
              color: #333;
            }

            .user-role {
              margin: 0;
              color: #999;
              font-size: 14px;
            }
          }
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;
          margin-bottom: 30px;

          .info-item {
            display: flex;
            flex-direction: column;

            label {
              font-weight: 500;
              color: #666;
              font-size: 14px;
              margin-bottom: 5px;
            }

            span {
              color: #333;
              font-size: 16px;
            }
          }
        }

        .actions {
          display: flex;
          justify-content: center;
          gap: 20px;
        }
      }

      .edit-mode {
        .avatar-section {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-bottom: 30px;

          .user-basic-info {
            text-align: center;
            margin-top: 15px;

            h3 {
              margin: 0 0 5px 0;
              color: #333;
            }

            .user-role {
              margin: 0;
              color: #999;
              font-size: 14px;
            }
          }
        }

        .form-grid {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 20px;
          margin-bottom: 30px;
        }

        .edit-actions {
          display: flex;
          justify-content: center;
          gap: 20px;
        }
      }
    }

    .error {
      text-align: center;
      padding: 50px 0;

      .error-icon {
        font-size: 48px;
        color: #f56c6c;
        margin-bottom: 15px;
      }

      p {
        color: #f56c6c;
        margin-bottom: 20px;
        font-size: 16px;
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .user-info-container {
    padding: 10px;

    .user-info-card {
      padding: 20px;

      .info-grid,
      .form-grid {
        grid-template-columns: 1fr;
      }

      .actions,
      .edit-actions {
        flex-direction: column;
        gap: 10px;
      }
    }
  }
}
</style>
